package com.itheima.controller.backend.security;

import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.Result;
import com.itheima.common.utils.AliOssUtil;
import com.itheima.common.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/setmeal/upload")
    public Result upload(MultipartFile file){
        log.info("文件上传:{}",file);

        try {
            //获取上传文件的名称及拓展名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //利用UUID构造新的文件名
            String objectName = UUID.randomUUID().toString() + extension;

            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            //将上传的文件名保存到Redis中，用于后续操作
            redisTemplate.opsForSet().add("uploadFile",objectName);

            return Result.success(filePath);
        } catch (IOException e) {
            log.error("上传失败:",e);
        }

        return Result.error(MessageConstant.PIC_UPLOAD_FAIL);
    }


}
